package com.lemon.smartsafetynew.ui.activity.base;

import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.ldzs.recyclerlibrary.view.FullyGridLayoutManager;
import com.lemon.android.http.HttpUtils;
import com.lemon.safecloud.greendao.PlayView;
import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.CommonAssetsVo;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.EvidenceItemVo;
import com.lemon.smartsafety.entity.common.FileType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.evidence.EvidenceDeleteEvent;
import com.lemon.smartsafety.entity.event.evidence.EvidenceItemEvent;
import com.lemon.smartsafety.entity.event.evidence.EvidencePlusEvent;
import com.lemon.smartsafety.entity.event.evidence.VoiceEvent;
import com.lemon.smartsafety.listener.GlidePauseOnScrollListener;
import com.lemon.smartsafety.ui.adapter.common.RcvViewType;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.ImageUtils;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.common.ViewUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.lemon.smartsafety.view.dialog.DialogChoice;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.squareup.leakcanary.RefWatcher;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.PauseOnScrollListener;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.galleryfinal.permission.AfterPermissionGranted;
import cn.finalteam.galleryfinal.permission.EasyPermissions;

/**
 * Created by Andrew on 2017/11/24.
 */

public abstract class PhotoSelectBaseTwoActivity extends SwipeBackActivity implements EasyPermissions.PermissionCallbacks {

    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;
    private final int REQUEST_CODE_CROP = 1002;
    private final int REQUEST_CODE_EDIT = 1003;
    private final int REQUEST_CODE_LOCATION = 1004;

    private SharedPreferencesServer mSharedPreferencesServer;

    private ThemeConfig mThemeConfig = null;
    private FunctionConfig.Builder mFunctionConfigBuilder = null;
    private CoreConfig.Builder mCoreConfigBuilder = null;

    private RecyclerView mSelectRecycleView;
    protected FullyGridLayoutManager mFullyGridLayoutManager;
    protected SelectEvidenceAdapter mSelectEvidenceAdapter;
    private int mColumnNumber = 0;
    /**
     * 注意获取数据 不要直接使用该变量使用 getListPhotoInfo();
     */
    protected List<EvidenceItemVo<PhotoInfo>> mPhotoList = new ArrayList<>();
    private List<PhotoInfo> mCropResult = new ArrayList<>();

    //是否可以多选
    private boolean bMultiSelect = true;
    //private boolean bMySingleSelect = false;

    /**
     * 是否不使用动画
     */
    private boolean bNoAnimation = true;

    /**
     * 最大的选择照片数量
     */
    private int mMaxSize = 9;

    private String tempString = "";


    protected String mAddress = null;
    protected String mLngLat = null;

    protected String mLng = null;
    protected String mLat = null;


    private DialogChoice dialogChoice = null;
    private Activity mActivity;
    private LocationUtil loacationUtil;

    private boolean isShowAdd = true;


    /**
     * @param showAdd 是否显示 添加相册的ACTION SHEET
     */
    public void setShowAdd(boolean showAdd) {
        isShowAdd = showAdd;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("mThemeConfig", mThemeConfig);
        outState.putSerializable("FunctionConfig_Builder", mFunctionConfigBuilder);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mThemeConfig = (ThemeConfig) savedInstanceState.getSerializable("mThemeConfig");
            mFunctionConfigBuilder = (FunctionConfig.Builder) savedInstanceState.getSerializable("FunctionConfig_Builder");
            initGalleryFinal();
        }
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
    }

    @Override
    public void baseOnCreate(Bundle savedInstanceState) {
        super.baseOnCreate(savedInstanceState);

        if (savedInstanceState == null) {
            initGalleryFinal();
        }
    }

    private void initGalleryFinal() {
        mSharedPreferencesServer = new SharedPreferencesServer(IApplication.context());

        mThemeConfig = new ThemeConfig.Builder().setTitleBarBgColor(getResources().getColor(R.color.colorPrimary))
                .setTitleBarTextColor(getResources().getColor(R.color.colorWhite))
                .setTitleBarIconColor(getResources().getColor(R.color.colorWhite))
                .setFabNornalColor(getResources().getColor(R.color.colorPrimary))
                .setCheckSelectedColor(getResources().getColor(R.color.colorPrimary))//选择框选中颜色
                .setFabPressedColor(getResources().getColor(R.color.colorPrimaryDark))
                .build();
        mFunctionConfigBuilder = new FunctionConfig.Builder();
        cn.finalteam.galleryfinal.ImageLoader imageLoader = new GlideImageLoader();
        PauseOnScrollListener pauseOnScrollListener = new GlidePauseOnScrollListener(false, true);
        mFunctionConfigBuilder.setMutiSelectMaxSize(mMaxSize);


        mFunctionConfigBuilder.setEnableEdit(false);
        mFunctionConfigBuilder.setEnableRotate(true);
        mFunctionConfigBuilder.setRotateReplaceSource(false);

        mFunctionConfigBuilder.setEnableCrop(false);
        mFunctionConfigBuilder.setCropReplaceSource(false);
        mFunctionConfigBuilder.setCropSquare(false);
        mFunctionConfigBuilder.setForceCrop(false);//启动强制裁剪功能,一进入编辑页面就开启图片裁剪，不需要用户手动点击裁剪，此功能只针对单选操作
        mFunctionConfigBuilder.setForceCropEdit(false);//在开启强制裁剪功能时是否可以对图片进行编辑（也就是是否显示旋转图标和拍照图标）
        mFunctionConfigBuilder.setEnableCamera(true);
        mFunctionConfigBuilder.setEnablePreview(false);

        mCoreConfigBuilder = new CoreConfig.Builder(IApplication.context(), imageLoader, mThemeConfig).setFunctionConfig(mFunctionConfigBuilder
                .build())
                .setPauseOnScrollListener(pauseOnScrollListener)
                .setNoAnimcation(bNoAnimation);

        mCoreConfigBuilder.setTakePhotoFolder(new File(Environment.getExternalStorageDirectory(), "/DCIM/" + Constants.APP_TEMP_DIR + "/"));

        mCoreConfigBuilder.setEditPhotoCacheFolder(new File(FileUtil.getAppImagesDir(IApplication.context())));

        GalleryFinal.init(mCoreConfigBuilder.build());
    }


    public void showActionSheet(EvidenceActionSheetType type) {

        try {
            GalleryFinal.init(mCoreConfigBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (dialogChoice == null) {
            dialogChoice = new DialogChoice(this);
        }


        if (EvidenceActionSheetType.ALBUM_VOICE == type) {//相册加录音，可以照相
            dialogChoice.init(this, "取消", new DialogChoice.ClickBackInterface() {
                @Override
                public void callBackFunction(View view, int index) {
                    if (index == 0) {//相册
                        bMultiSelect = true;
                        mFunctionConfigBuilder.setEnableCamera(true);
                        showSelectPhotoView(false);
                    } else if (index == 1) {
                        goVoiceRecord();
                    }
                }
            }, "相册", "录音");

        } else if (EvidenceActionSheetType.CAMERA_SINGLE == type) {//相机单选，一般用于头像
            dialogChoice.init(this, "取消", new DialogChoice.ClickBackInterface() {
                @Override
                public void callBackFunction(View view, int index) {
                    if (index == 0) {//相机
                        bMultiSelect = false;
                        mFunctionConfigBuilder.setEnableEdit(false);
                        GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                    }
                }
            }, "相机");

        } else if (EvidenceActionSheetType.CAMERA_ALBUM_SINGLE == type) {
            dialogChoice.init(this, "取消", new DialogChoice.ClickBackInterface() {
                @Override
                public void callBackFunction(View view, int index) {
                    if (index == 0) {//相机
                        bMultiSelect = false;
                        mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                        GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                    } else if (index == 1) {
                        showSingleSelectAndCamera();
                    }
                }
            }, "相机", "相册");

        } else if (EvidenceActionSheetType.CAMERA_VOICE == type) {
            dialogChoice.init(this, "取消", new DialogChoice.ClickBackInterface() {
                @Override
                public void callBackFunction(View view, int index) {
                    try {
                        if (index == 0) {//相机
                            bMultiSelect = true;
                            mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                        } else if (index == 1) {
                            goVoiceRecord();
                        }
                    } catch (Exception e) {
                        if (BuildConfig.DEBUG) {
                            //BuglyLog.d("PhotoSelectBaseActivity", e.getLocalizedMessage());
                            e.printStackTrace();
                        }
                    }
                }
            }, "相机", "录音");

        } else if (EvidenceActionSheetType.CAMERA_ALBUM_MULTI == type) {
            dialogChoice.init(this, "取消", new DialogChoice.ClickBackInterface() {
                @Override
                public void callBackFunction(View view, int index) {
                    try {
                        if (index == 0) {//相机
                            bMultiSelect = true;
                            mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                        } else if (index == 1) {
                            bMultiSelect = true;
                            mFunctionConfigBuilder.setEnableCamera(true);
                            showSelectPhotoView(false);
                        }
                    } catch (Exception e) {
                        if (BuildConfig.DEBUG) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "相机", "相册");

        } else if (EvidenceActionSheetType.CAMERA_ALBUM_VOICE == type) { // add by Andrew.yin 2017/10/18
            dialogChoice.init(this, "取消", new DialogChoice.ClickBackInterface() {
                @Override
                public void callBackFunction(View view, int index) {
                    try {

                        if(index == 0) { //照相机
                            bMultiSelect = true;
                            mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                            GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                        } else if (index == 1) {//相册
                            bMultiSelect = true;
                            mFunctionConfigBuilder.setEnableCamera(true);
                            showSelectPhotoView(false);
                        } else if (index == 2) {
                            goVoiceRecord();
                        }

                    } catch (Exception e) {
                        if (BuildConfig.DEBUG) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "相机", "相册", "录音");

        }

    }

    public void goVoiceRecord() {
        UIHelper.showVoiceRecordActivity(PhotoSelectBaseTwoActivity.this, this.getClass().getName());
    }

    @Override
    protected void initViews() {
        super.initViews();
        mActivity = this;
        mPhotoList = new ArrayList<>();
        mCropResult = new ArrayList<>();
        mSelectEvidenceAdapter = new SelectEvidenceAdapter(mPhotoList, true, this.getClass().getName());
        //突出是
        mSelectRecycleView = getViewById(R.id.mSelectRecycleView);
        if (mSelectRecycleView != null) {
            mFullyGridLayoutManager = new FullyGridLayoutManager(this, getColumnNumber());
            mSelectRecycleView.setLayoutManager(mFullyGridLayoutManager);
            mSelectRecycleView.setAdapter(mSelectEvidenceAdapter);
        }
        loacationUtil = new LocationUtil(this);
        loacationUtil.getLoacation(new LocationUtil.CallBackInterface() {
            /**
             *
             */
            @Override
            public void callBackFunction() {
                mAddress = loacationUtil.getmAddress();
                if (!CommonUtil.strIsEmpty(mAddress)) {
                    mAddress = mAddress.replace(loacationUtil.getmCountry(), "");
                }
                mLngLat = loacationUtil.getmLngLat();
                mLng = loacationUtil.getmLng();
                mLat = loacationUtil.getmLat();

                if (null != mSelectEvidenceAdapter && StringUtils.nullValue(mAddress).length() != 0) {
                    mSelectEvidenceAdapter.setWaterText(getWaterString());
                }

            }
        });


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initAMap();
            }
        }, 1000);
    }

    public void setSelectEnable(boolean enable) {
        if (mSelectRecycleView != null) {
            mSelectRecycleView.setVisibility(enable ? View.VISIBLE : View.GONE);
        }
    }


    public boolean hasEvidence() {
        if (mSelectEvidenceAdapter != null) {
            if (mSelectEvidenceAdapter.isCanAdd()) {
                return mSelectEvidenceAdapter.getData().size() <= 1 ? false : true;
            } else {
                return mSelectEvidenceAdapter.getData().size() <= 0 ? false : true;
            }
        }
        return false;
    }

    public int getColumnNumber() {
        if (mColumnNumber == 0) {
            mColumnNumber = getColumnByScreen();
        }
        return mColumnNumber;
    }

    public int getColumnByScreen() {
        int screenWidthDP = ViewUtils.getScreenWidthDP(this) - 20;//左右边距10dp
        int itemWidthDP = ViewUtils.px2dip(this, (int) getResources().getDimension(R.dimen.evidence_item_size));
        //商
        int column = screenWidthDP / itemWidthDP;
        /**
         * 余数
         */
        int remainders = screenWidthDP % itemWidthDP;
        if ((remainders / column) < 10) {
            column = column - 1;
        }
        return column;
    }

    /**
     * 根据屏幕来获取列数
     */
    public void setColumnNumber() {
        setColumnNumber(getColumnByScreen());
    }

    /**
     * 根据屏幕来获取列数
     *
     * @param columnNumber
     */
    public void setColumnNumber(int columnNumber) {
        mColumnNumber = columnNumber;
        mFullyGridLayoutManager = new FullyGridLayoutManager(this, mColumnNumber);
        mSelectRecycleView.setLayoutManager(mFullyGridLayoutManager);
        mSelectEvidenceAdapter.notifyItemRangeChanged(0, mPhotoList.size() - 1);
    }

    /**
     * 动态添加证据视图
     *
     * @param items
     */
    public void addItems(List<EvidenceItemVo<PhotoInfo>> items) {
        setColumnNumber();
        mSelectEvidenceAdapter.addItems(items);
    }


    //public abstract EvidenceActionSheetType getActionSheetType();

    /**
     * 添加按钮事件处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(EvidencePlusEvent event) {
        if (isShowAdd) {
            evidencePlusEventHandler(event.getTag());
        }
    }


    /**
     * 弹出选择框 照相，相册，录音
     * @param tag
     */
    public void evidencePlusEventHandler(String tag) {
        bMultiSelect = true;//加号都多选
        //changed by Andrew.yin 2017/10/18 begin
        //showActionSheet(EvidenceActionSheetType.ALBUM_VOICE);
        showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_MULTI);
        //changed by Andrew.yin 2017/10/18 end
    }

    /**
     * 选择照片
     *
     * @param selected 是否初始化之前选择的
     */
    public void showSelectPhotoView(boolean selected) {
        if (selected) {
            showSelectPhotoActivity(getListPhotoInfo(mPhotoList));
        } else {
            showSelectPhotoActivity(null);
        }
    }

    public void showSelectSinglePhotoView() {
        bMultiSelect = false;
        mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
        showSelectPhotoActivity(null);
    }


    /**
     * 单张图片选择还带照相机功能
     */
    public void showSingleSelectAndCamera() {
        bMultiSelect = false;
        mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
        mFunctionConfigBuilder.setEnableCamera(true);
        GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
    }

    /**
     * 显示照片选择
     */
    public void showSelectPhotoActivity(List<PhotoInfo> selectedPhotos) {
        if (selectedPhotos != null && !selectedPhotos.isEmpty()) {
            mFunctionConfigBuilder.setSelected(selectedPhotos);
            mCoreConfigBuilder.setFunctionConfig(mFunctionConfigBuilder.build());
        }
        GalleryFinal.init(mCoreConfigBuilder.build());
        if (bMultiSelect) {
            GalleryFinal.openGalleryMuti(REQUEST_CODE_GALLERY, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
        } else {
            GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
        }
    }

    /**
     * 把获取材料数据专程选择时候用的
     *
     * @param list
     * @return
     */
    public List<PhotoInfo> getListPhotoInfo(List<EvidenceItemVo<PhotoInfo>> list) {
        List<PhotoInfo> result = new ArrayList<>();
        for (int i = 0; list != null && i < list.size(); i++) {
            EvidenceItemVo<PhotoInfo> vo = list.get(i);
            if (RcvViewType.EvidenceViewType.TYPE_ADD != vo.getViewType()) {
                result.add(vo.getData());
            }
        }
        return result;
    }

    /**
     * 用于获取所有的图片项目
     *
     * @param list
     * @return
     */
    public List<PhotoInfo> getPhotoViewList(List<EvidenceItemVo<PhotoInfo>> list) {
        List<PhotoInfo> result = new ArrayList<>();
        for (int i = 0; list != null && i < list.size(); i++) {
            EvidenceItemVo<PhotoInfo> vo = list.get(i);
            if (RcvViewType.EvidenceViewType.TYPE_PHOTO == vo.getViewType()) {
                result.add(vo.getData());
            }
        }
        return result;
    }


    /**
     * 把材料数据转换成ListView视图数据
     *
     * @param list
     * @return
     */
    public List<EvidenceItemVo<PhotoInfo>> getEvidenceListByPhotoInfo(List<PhotoInfo> list) {
        List<EvidenceItemVo<PhotoInfo>> result = new ArrayList<>();
        for (int i = 0; list != null && i < list.size(); i++) {
            EvidenceItemVo<PhotoInfo> vo = new EvidenceItemVo<>();
            vo.setViewType(RcvViewType.EvidenceViewType.TYPE_PHOTO);
            vo.setData(list.get(i));
            result.add(vo);
        }
        return result;
    }

    public List<EvidenceItemVo<PhotoInfo>> getEvidenceItems() {
        if (mSelectEvidenceAdapter != null) {
            return mSelectEvidenceAdapter.getItems();
        }
        return null;
    }


    public void setMultiSelect(boolean multi) {
        this.bMultiSelect = multi;
    }


    public void setNoAnimation(boolean animation) {
        this.bNoAnimation = animation;
        mCoreConfigBuilder.setNoAnimcation(this.bNoAnimation);
    }


    /**
     * 普通项目点击事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(EvidenceItemEvent event) {
        if (EventTag.TAG_EVIDENCE_ITEM.equals(event.getTag())) {
            if (RcvViewType.EvidenceViewType.TYPE_PHOTO == event.getType()) {//照片预览
                List<PhotoInfo> photos = getPhotoViewList(mPhotoList);
                if (photos != null && photos.size() != 0) {
                    int currentItem = 0;
                    for (int i = 0; i < photos.size(); i++) {
                        PhotoInfo photoInfo = photos.get(i);
                        if (StringUtils.nullValue(event.getUrl())
                                .equalsIgnoreCase(StringUtils.nullValue(photoInfo.getPhotoPath()))) {
                            currentItem = i;
                            break;
                        }
                    }
                    UIHelper.showPhotoView(this, photos, currentItem);
                }
            } else if (RcvViewType.EvidenceViewType.TYPE_VOICE == event.getType()) {//音频播放
                playVoice(HttpUtils.formatFilesUrl(event.getUrl()));
            }
        }
    }

    /**
     * 删除按钮事件处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(EvidenceDeleteEvent event) {
        mSelectEvidenceAdapter.removeEvidenceItems(event.getItem());
    }


    /**
     * 录音返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(VoiceEvent event) {
        if (this.getClass().getName().equals(event.getTag())) {
            String url = event.getUrl();
            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setPhotoId(new Random(1000).nextInt() + 1);
            photoInfo.setPhotoPath(url);
            EvidenceItemVo<PhotoInfo> vo = new EvidenceItemVo<>();
            vo.setViewType(RcvViewType.EvidenceViewType.TYPE_VOICE);
            vo.setData(photoInfo);
            mSelectEvidenceAdapter.addEvidenceItem(vo);
        }
    }

    public void addPlayViewItems(List<PlayView> items) {
        if (null == items) {
            return;
        }
        List<EvidenceItemVo<PhotoInfo>> result = new ArrayList<>();
        for (int i = 0; items != null && i < items.size(); i++) {
            PlayView item = items.get(i);
            EvidenceItemVo<PhotoInfo> itemVo = new EvidenceItemVo<>();
            itemVo.setFid(item.getId() + "");
            itemVo.setOp(UploadFileItem.COM);
            itemVo.setUrl(item.getUrl());
            itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_PHOTO);

            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setPhotoId(items.size() + i);
            photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(item.getUrl()));

            itemVo.setData(photoInfo);
            result.add(itemVo);
        }
        mSelectEvidenceAdapter.addEvidenceItems(result);
    }


    /**
     * 多类型添加方法
     *
     * @param items
     */
    public void addAllItems(List items) {
        if (null == items && items.size() == 0) {
            return;
        }
        List<EvidenceItemVo<PhotoInfo>> result = new ArrayList<>();
        for (int i = 0; items != null && i < items.size(); i++) {

            Object item = items.get(i);
            if (item instanceof CommonAssetsVo) {
                CommonAssetsVo vo = (CommonAssetsVo) item;
                EvidenceItemVo<PhotoInfo> itemVo = new EvidenceItemVo<>();
                itemVo.setFid(vo.getVoId() + "");
                itemVo.setOp(UploadFileItem.COM);
                itemVo.setUrl(vo.getDataUrl());
                if (LemonFileHelper.isImageUrl(vo.getDataUrl())) {
                    itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_PHOTO);
                } else if (LemonFileHelper.isVoiceUrl(vo.getDataUrl())) {
                    itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_VOICE);
                } else if (LemonFileHelper.isVideoUrl(vo.getDataUrl())) {
                    itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_VIDEO);
                }
                PhotoInfo photoInfo = new PhotoInfo();
                photoInfo.setPhotoId(items.size() + i);
                photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(vo.getDataUrl()));

                itemVo.setData(photoInfo);
                result.add(itemVo);
            } else if (item instanceof PlayView) {
                PlayView playView = (PlayView) item;
                EvidenceItemVo<PhotoInfo> itemVo = new EvidenceItemVo<>();
                itemVo.setFid(playView.getId() + "");
                itemVo.setOp(UploadFileItem.COM);
                itemVo.setUrl(playView.getUrl());

                if (LemonFileHelper.isImageUrl(playView.getUrl())) {
                    itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_PHOTO);
                } else if (LemonFileHelper.isVoiceUrl(playView.getUrl())) {
                    itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_VOICE);
                } else if (LemonFileHelper.isVideoUrl(playView.getUrl())) {
                    itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_VIDEO);
                }
                //itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_PHOTO);

                PhotoInfo photoInfo = new PhotoInfo();
                photoInfo.setPhotoId(items.size() + i);
                photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(playView.getUrl()));

                itemVo.setData(photoInfo);
                result.add(itemVo);
            }
        }
        mSelectEvidenceAdapter.addEvidenceItems(result);
    }


    /**
     * 移除所有的加载照片
     */
    public void removeLoadFileItems() {
        mSelectEvidenceAdapter.removeAll();
    }


    /**
     * 将网络那边获取的UploadFileItem 对象添加到证据视图
     *
     * @param items
     */
    public void addUploadFileItems(List<UploadFileItem> items) {
        if (null == items || items.isEmpty()) {
            return;
        }
        List<EvidenceItemVo<PhotoInfo>> result = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            UploadFileItem item = items.get(i);
            EvidenceItemVo<PhotoInfo> itemVo = new EvidenceItemVo<>();
            itemVo.setFid(item.getFid());
            itemVo.setType(item.getType());
            if (FileType.PHOTO.getValue().equals(item.getType())) {
                itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_PHOTO);
            } else if (FileType.VOICE.getValue().equals(item.getType())) {
                itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_VOICE);
            } else if (FileType.VIDEO.getValue().equals(item.getType())) {
                itemVo.setViewType(RcvViewType.EvidenceViewType.TYPE_VIDEO);
            }
            itemVo.setOp(item.getOp());
            itemVo.setUrl(item.getUrl());
            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setPhotoId(items.size() + i);
            photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(item.getUrl(), mSharedPreferencesServer.getFilesUrl()));

            itemVo.setData(photoInfo);
            result.add(itemVo);
        }
        mSelectEvidenceAdapter.addEvidenceItems(result);
    }


    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (bMultiSelect) {
                List<EvidenceItemVo<PhotoInfo>> result = getEvidenceListByPhotoInfo(resultList);
                mSelectEvidenceAdapter.addEvidenceItems(result);
            } else {
                onSinglePhotoSuccess(reqeustCode, resultList.get(0));
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            mHUDUtil.showErrorTip(errorMsg);
        }
    };


    protected void onSinglePhotoSuccess(int requestCode, PhotoInfo photoInfo) {

    }

    /**
     * 获取需要上传的表单信息
     *
     * @param callBack
     */
    public void getUploadItems(SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>> callBack) {
        if (mSelectEvidenceAdapter != null && callBack != null) {
            mSelectEvidenceAdapter.getUploadItems(callBack);
        }
    }

    public void getSinglePhotoUploadItem(PhotoInfo photoInfo, final SelectEvidenceAdapter.CropCallBack<String> callBack) {
        if (callBack == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    callBack.onStart();
                }
            }
        });
        if (photoInfo == null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callBack.onFinish("");
                }
            });
            return;
        }
        final String oldPath = StringUtils.nullValue(photoInfo.getPhotoPath());
        if (oldPath.length() == 0 || oldPath.startsWith("http://") || oldPath.startsWith("https://")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callBack.onFinish("");
                }
            });
            return;
        }
        final String newPath = FileUtil.getFullPhotoPath(IApplication.context());
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = ImageUtils.decodeBitmap(oldPath, newPath, Constants.IMAGE_VIEW_WIDTH, Constants.IMAGE_VIEW_HEIGHT, getWaterString());
                tempString = "";
                if (result) {
                    tempString = ImageUtils.getImageBase64Code(newPath);
                }
                tempString = StringUtils.nullValue(tempString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callBack != null) {
                            callBack.onFinish(tempString);
                        }
                    }
                });
            }
        }).start();
    }


    /**
     * 定位相关
     */
    private void initAMap() {

        doLocation();
    }

    @AfterPermissionGranted(REQUEST_CODE_LOCATION)
    private void doLocation() {
        //ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION
        String[] perms = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(this, perms)) {
            doLocationAction();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "App申请访问你的位置信息", REQUEST_CODE_LOCATION, perms);
        }
    }

    private void doLocationAction() {

    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        if (requestCode == REQUEST_CODE_LOCATION) {
            doLocationAction();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        if (requestCode == REQUEST_CODE_LOCATION) {
            showToast("请打开gps访问权限后使用该功能");
        }
    }


    public String getWaterString() {
        //changed by Andrew.yin 2017/8/28 begin
//        String water = mSharedPreferencesHelper.getUserName() + " / " + DateUtils.getCurrentYMDHMSDate() + "\r\n" + StringUtils
//                .nullValue(mAddress)
//                .trim();

        String userName = "";
        User user = null;
        user = AccountUtil.getUser();
        if (user != null) {
            userName = user.getUserName();
        }

        String water = userName + " / " + DateUtils.getCurrentYMDHMSDate() + "\r\n" + StringUtils
                .nullValue(mAddress)
                .trim();
        //changed by Andrew.yin 2017/8/28 end

        Log.v("THE　TIME IS：", water);
        return StringUtils.nullValue(water);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            IApplication._tempOneActivity = null;
            AppManager.getAppManager().finishActivity(mActivity);
            System.gc();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = IApplication.getRefWatcher();
        refWatcher.watch(this);
        try {
            loacationUtil.onDestroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            mHUDUtil.hidden();
            mHUDUtil.hiddenDelay();
            LogUtils.LOGE("注销弹框");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void setMaxSize(int maxSize) {
        this.mMaxSize = maxSize;
        if (mFunctionConfigBuilder != null) {
            mFunctionConfigBuilder.setMutiSelectMaxSize(maxSize);
        }
    }


    //add by Andrew.yin 2017/9/22 begin
    public void getUploadMediaItems(SelectEvidenceAdapter.CropCallBack<Map<String, File>> callBack) {

        if (callBack != null) {
            callBack.onStart();
        } else {
            return;
        }

        try {

            Map<String, File> fileMap = new HashMap<>();

            List<EvidenceItemVo<PhotoInfo>> evidenceItemVos = mSelectEvidenceAdapter.getData();

            int size = evidenceItemVos.size();

            if (size >= 1) {
                size = size - 1;
            }

            if (size == 0) {  //一个文件都没有直接完成
                callBack.onFinish(fileMap);
                return;
            }

            for (int i = 0; i < size; i++) {

                PhotoInfo photo = evidenceItemVos.get(i).getData();
                String newPath = FileUtil.getFullPhotoPath(IApplication.context());
                String oldPath = StringUtils.nullValue(photo.getPhotoPath());

                if (oldPath.length() == 0) {  //附件的加号
                    continue;
                }

                if (LemonFileHelper.isVoiceUrl(oldPath)) {
                    fileMap.put(FileUtil.getFileName(oldPath), new File(oldPath));
                } else if (LemonFileHelper.isImageUrl(oldPath)) {
                    boolean result = ImageUtils.decodeBitmap(oldPath, newPath, Constants.IMAGE_VIEW_WIDTH, Constants.IMAGE_VIEW_HEIGHT, mSelectEvidenceAdapter.getWaterText());
                    if (result) {
                        fileMap.put(FileUtil.getFileName(newPath), new File(newPath));
                    }
                }

            }

            callBack.onFinish(fileMap);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //add by Andrew.yin 2017/9/22 end
}
